<template>
	<view>
		<modal class="getAuthor" v-if="showModal" :confirm-text="none" :cancel-text="none">
		  <view class='header'>坤瑞恒建材有限公司</view>
		  <view class='content'>
		      <view>申请获取以下权限</view>
		      <text>获得你的公开信息(昵称，头像，地区等)</text>
		  </view>
		  <button class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" @tap="bindGetUserInfo">登录</button>
		</modal>
	</view>
</template>

<script>
	import URL from '../../../utils/baseurl.js'
	export default {
		data() {
			return {
				showModal: false
			};
		},
		methods:{
			login(){
				let self = this;
				uni.login({
				  complete: (res) => {
					console.log(res, '用户授权code：' + res.code);
					// this.config.post('/weixin/login/login1', {
					this.config.post('/weixin/login/getsessionKey', {
						code: res.code,
					}).then(res=>{
						uni.hideLoading();
						if(res.data.code==='0'){
							uni.setStorageSync('token', res.data.token); // 本地储存token
							self.config.header['token'] = uni.getStorageSync('token'); // 修改header参数
							
							self.showModal = true;
						}else{
							uni.showToast({title: self.config.handleError(res.data),icon: 'none'});
						}
					})
				  },
				})
			},
			// 获取用户信息
			bindGetUserInfo(){
				let self = this;
				uni.getUserInfo({
				  success: (res) => {
					console.log(res, '用户主动授权')
					self.userInfo = res.userInfo;
					self.getOpenid(res)
					// self.getGeoLocation();
				  },
				  fail(res){
					uni.setStorageSync('sessionId', '');
				  }
				})
			},
			// 验证登录
			getOpenid(xdata){
				let self = this;
				uni.request({
				  url: self.URL +'/weixin/login/info',
				  data: {
					rawData: xdata.rawData,
					signature: xdata.signature,
					encryptedData: xdata.encryptedData,
					iv: xdata.iv
				  },
				  header: self.config.header,
				  method: 'post',
				  success(res){
					console.log(res.data, '后台获取信息')
					if(res.data.code=='0'){
					  if(res.data.user){ // 如果用户绑定了手机号
						// self.config.globalData.userInfo.mobile = res.data.user.mobile;
						self.config.globalData.user = res.data.user;
						if(res.data.isNeedRealName){
							uni.navigateTo({
							  url: '/pages/main/bindMobile/bindMobile',
							})
						}else{
							uni.switchTab({
							  url: '/pages/home/home',
							})
						}
						// uni.$emit('userInfo', 'ok')
					  } else { // 如果用户没有绑定
						self.showModal = false;
						// self.showphone = true;
					  }
					}
				  }
				})
			},
		},
		mounted() {
			this.login()
		}
	}
</script>

<style lang="less">

</style>
